# app/core/security.py

import hashlib
import hmac
import time
from typing import Optional
from config.settings import settings

def validate_api_key(api_key: str) -> bool:
    """验证API密钥"""
    # 这里可以实现更复杂的API密钥验证逻辑
    return api_key == settings.BAILIAN_API_KEY

def generate_signature(data: str, secret: str) -> str:
    """生成签名"""
    return hmac.new(
        secret.encode('utf-8'),
        data.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()

def verify_signature(data: str, signature: str, secret: str) -> bool:
    """验证签名"""
    expected_signature = generate_signature(data, secret)
    return hmac.compare_digest(signature, expected_signature)

def sanitize_filename(filename: str) -> str:
    """清理文件名，移除危险字符"""
    import re
    # 移除或替换危险字符
    sanitized = re.sub(r'[<>:"/\\|?*]', '_', filename)
    # 限制长度
    if len(sanitized) > 255:
        name, ext = os.path.splitext(sanitized)
        sanitized = name[:255-len(ext)] + ext
    return sanitized

def validate_file_path(file_path: str) -> bool:
    """验证文件路径安全性"""
    import os
    # 检查路径遍历攻击
    normalized_path = os.path.normpath(file_path)
    if '..' in normalized_path:
        return False
    
    # 检查绝对路径
    if os.path.isabs(normalized_path):
        return False
    
    return True

def rate_limit_check(client_id: str, limit: int = 100, window: int = 3600) -> bool:
    """简单的速率限制检查"""
    # 这里可以实现更复杂的速率限制逻辑
    # 例如使用Redis存储请求计数
    return True 